package com.xf.auth.handler;

import com.xf.common.core.entity.FebsResponse;
import com.xf.common.core.utils.FebsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author xufeng
 *
 */
@Component
@Slf4j
public class FebsWebLoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException {
        //可以记录入库 后面做统计功能.发通知到该账户告警等操作
        log.info(String.format("IP %s 于 %s 尝试登录系统失败，失败原因：%s", httpServletRequest.getRemoteHost(), LocalDateTime.now(), exception.getMessage()));
        int status = HttpServletResponse.SC_UNAUTHORIZED;
        httpServletResponse.setStatus(status);
        String message;
        if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误！";
        } else if (exception instanceof LockedException) {
            message = "用户已被锁定！";
        } else {
            message = "认证失败，请联系网站管理员！";
        }
        FebsResponse febsResponse = new FebsResponse().message(message).code("1000");
        FebsUtil.makeFailureResponse(httpServletResponse, febsResponse);
    }
}
